﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Linq.Expressions;
using Cherry.Agile.Data.Metadata;
using System.Data.Objects.DataClasses;
using System.Configuration;
using System.Data.EntityClient;
using System.IO;
using Cherry.Agile.Data.Object.Metadata;

namespace Cherry.Agile.Data.Internal
{
    /// <summary>
    /// Extensions methods in ObjectQuery
    /// </summary>
    internal static class ObjectQueryExtensions
    {
        #region ObjectQuery Extensions Methods

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="objectQuery"></param>
        /// <param name="setExpression"></param>
        /// <param name="whereExpression"></param>
        /// <returns></returns>
        public static int UpdateAll<T>(this ObjectContext context, Expression<Func<T, T>> setExpression,
            Expression<Func<T, bool>> whereExpression )
            where T:class
        {

            MetadataAccessor.PopulateMetadata<T>(context); 
             
            DmlExpressionParser<T> updateExpressionParser = new UpdateExpressionParser<T>(context.DefaultContainerName,
                                setExpression, whereExpression);

            string script = updateExpressionParser.GetDmlCommand(); 

            System.Diagnostics.Trace.TraceInformation("ObjectQueryExtensions\t" + script);

            return context.ExecuteStoreCommand(script);
        }

        //public static int InsertAll<T>(this ObjectContext context, 
        //    Expression<Func<T, T>> insertExpresion) where T : class
        //{
        //    MetadataAccessor.PopulateMetadata<T>(context); 
        //}
       
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="objectQuery"></param>
        /// <param name="whereExpression"></param>
        /// <returns></returns>
        public static int DeleteAll<T>(this ObjectContext context, Expression<Func<T, bool>> whereExpression)
            where T:class
        {
            
            MetadataAccessor.PopulateMetadata<T>(context); 
         
            DmlExpressionParser<T> deleteExpressionParser = new DeleteExpressionParser<T>( context.DefaultContainerName,whereExpression);

            string script = deleteExpressionParser.GetDmlCommand();
    
            System.Diagnostics.Trace.TraceInformation("ObjectQueryExtensions\t" + script);

            return context.ExecuteStoreCommand(script);
        
        }
        #endregion

        #region Private Methods

  

        #endregion
    }
}
